package com.qianlou.qrcode.servlets;

import com.github.hui.quick.plugin.qrcode.wrapper.QrCodeGenWrapper;
import com.github.hui.quick.plugin.qrcode.wrapper.QrCodeOptions;
import com.google.zxing.WriterException;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.MultipartConfig;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;

@WebServlet("/github-generate-qrcode-with-bg")
@MultipartConfig(
        fileSizeThreshold = 1024 * 1024 * 2,
        maxFileSize = 1024 * 1024 * 10,
        maxRequestSize = 1024 * 1024 * 100)
public class GithubGenerateQRCodeWithBg extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String text = req.getParameter("text");
        String opacity = req.getParameter("opacity");
        if (opacity == null || opacity.isEmpty()) {
            opacity = "0.5f";
        }
        try {
            //背景图二维码
            BufferedImage image = QrCodeGenWrapper.of(text)
                    .setBgImg(req.getPart("logo").getInputStream())
                    .setBgOpacity(Float.parseFloat(opacity) / 100f)
                    .asBufferedImage();

            ImageIO.write(image, "png", resp.getOutputStream());
        } catch (WriterException e) {
            e.printStackTrace();
        }
    }
}
